package com.datounet.flutterapp;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;

import java.util.Locale;

public class NativeTTSMgr {
    private static String TAG = "NativeTTSMgr";
    private static TextToSpeech textToSpeech;
    private static int initStatus, setLanStatus;

    public static void init(Context context) {

    }

    public static void initAndSpeak(String txt) {
        release();
        textToSpeech = new TextToSpeech(MyApplication.getInstance(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                initStatus = status;
                // 设置音调,1.0是常规
                if (status == TextToSpeech.SUCCESS) {
                    textToSpeech.setPitch(1.0f);
                    //设定语速 ，默认1.0正常语速
                    textToSpeech.setSpeechRate(1.0f);
                    int result = textToSpeech.setLanguage(Locale.CHINA);
                    setLanStatus = result;
                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Toast.makeText(MyApplication.getInstance(), "暂不支持tts", Toast.LENGTH_LONG).show();
                    }else {
                        textToSpeech.speak(txt, TextToSpeech.QUEUE_ADD, null);

                    }
                }

            }
        });
    }

    public static void stop() {
        if (textToSpeech == null || TextToSpeech.SUCCESS != initStatus || TextToSpeech.LANG_AVAILABLE != setLanStatus) {
            Log.e(TAG, "初始化失败");
            return;
        }
        if (!textToSpeech.isSpeaking()) {
            return;
        }
        textToSpeech.stop();
    }

    public static void release() {
        if (textToSpeech == null || TextToSpeech.SUCCESS != initStatus || TextToSpeech.LANG_AVAILABLE != setLanStatus) {
            Log.e(TAG, "初始化失败");
            return;
        }
        textToSpeech.shutdown();
        textToSpeech = null;
    }
}
